﻿@{
    ViewBag.Title = "DeliveryRmo";
}

@section scripts
{   
    <script src="@Url.Content("~/Scripts/shared/share.js")" type="text/javascript"></script> 
    <script src="@Url.Content("~/Scripts/shared/shown.js?ver=GetDate()")" type="text/javascript"></script>      
    <script src="@Url.Content("~/Scripts/zxx.drag.1.0.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/common/Print.js?ver=GetDate()")" type="text/javascript"></script>
    <link href="~/Scripts/miniui/themes/default/medium-mode.css" rel="stylesheet" type="text/css" />       
    <style type="text/css">
        .window-mask {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                filter: alpha(opacity=40);
                opacity: 0.40;
                font-size: 1px;
                overflow: hidden;
                display:none;
                background-color: gray;
            }
    </style>
}
<body>
   <form id="form1" runat="server" method="post" style="height: 100%">
    
<div class="mini-toolbar" style="padding:2px;border-top:0;border-left:0;border-right:0;"> 
    <table width = "1000px;">
        <tr>
            <td width = "1000px;">
                <a class="mini-button" id="new" name="new" iconCls="icon-new" onclick="NewBill" plain="true" visible="@ViewBag.save">新增</a>
                <a class="mini-button" id="save" name="save" iconCls="icon-save" onclick="saveBill" plain="true" visible="@ViewBag.save">保存</a>                                
                <a class="mini-button" id="addrow" name="addrow" iconCls="icon-addnew" onclick="addRow" plain="true" visible="@ViewBag.save">增行</a>
                <a class="mini-button" id="delrow" name="delrow" iconCls="icon-remove" onclick="removeRow" plain="true" visible="@ViewBag.save">删行</a>                
                <a class="mini-button" id="modify" name="modify" iconCls="icon-edit" onclick="modify" plain="true" visible="@ViewBag.save">改单</a>
                <a class="mini-button" id="check" name="check" iconCls="icon-ok" onclick="checkBill" plain="true" visible="@ViewBag.check">出库审核</a>
                <a class="mini-button" id="Approve" name="Approve" iconCls="icon-ok" onclick="ApproveBill" plain="true" visible="@ViewBag.approve">入库审批</a>                
                <a class="mini-menubutton" plain="true" iconCls="icon-expand" menu="#popupMenu">选项</a>
                <a class="mini-button" id="print" iconCls="icon-print" onclick="printBillMyseft" plain="true" visible="@ViewBag.print">打印</a>
                <a class="mini-button" id="getdata" iconCls="icon-collapse" onclick="getBillData" plain="true">浏览</a>
                <span class="separator"></span>
                <a class="mini-button" id="close" iconCls="icon-close" onclick="CloseWindowBill" plain="true">关闭</a>
            </td>
        </tr>
    </table>                 
</div>
    
    <div id = "DivHeader">
        <table style="width:770px;">
            <tr>
                <td width ="80px" align="right">收货门店：</td>
                <td width ="190px">    
                    @Html.Partial("~/Views/Delivery/LookupStockRelevant.cshtml")
                </td>
                <td width ="80px" align="right">开单日期：</td>
                <td width ="190px">    
                    <input name="FDate" class="mini-datepicker" style="width:190px;"/>
                </td>
                 <td width ="80px" align="right">单据编号：</td>
                 <td width ="150px">    
                    <input name="FBillNo" class="mini-textbox" required="true"readonly="readonly"style="width:150px;"/>
                 </td>
            </tr>
            <tr>
                <td align="right">配送门店：</td>
                <td >
                    @Html.Partial("~/Views/Modular/LookupStockData.cshtml")                    
                </td>
                <td align="right">单据备注：</td>                    
                <td >  
                    <input name="FRemark" class="mini-textbox"  style="width:190px;"/>  
                </td>
                <td align="right">单据状态：</td>
                <td >    
                    <input name="txtCheckFlag" class="mini-textbox" readonly="readonly"style="width:150px;"/></td>
            </tr>
        </table>
    </div>
    <div class="mini-fit">
        <div id="datagrid1" class="mini-datagrid" style="width:100%;height:100%;" 
            showPager = "false" showPageSize="false" showPageIndex="false" skipReadOnlyCell="true"
            allowCellSelect="true" allowSortColumn = "false" allowCellEdit="true" navEditMode="true"
            editNextOnEnterKey="true"  editNextRowCell="false" showSummaryRow="true"
            ondrawcell="onDrawCell" oncellcommitedit="onCellCommitEdit" ondrawsummarycell="onDrawSummaryCell"
            onrowdblclick="onRowDblClick" fitColumns="false" oncelleditenter="onCelleditenter">
            <div property="columns">            
                <div type="indexcolumn" width="35" headerAlign="center" >序号</div>
                <div field="mFNumber" name="mFNumber" displayField = "mFNumber" width="120" headerAlign="center">商品编码
                <input property="editor" class="mini-buttonedit" onbuttonclick = "onButtonEdit" onvaluechanged = "onValueChanged" style="width:100%;"/>
                </div>  
                <div field="mFName" name="mFName" width="160" headerAlign="center">商品名称</div>  
                <div field="mFModel" name="mFModel" width="100" headerAlign="center">规格型号</div>
                <div field="mFUnitName" name="mFUnitName" width="40" headerAlign="center">单位</div>                
                <div field="mFQty" name="mFQty" width="70" headerAlign="center" align="right">数量
                    <input property="editor" class="mini-spinner" maxValue="99999999" style="width:100%;"changeOnMousewheel ="false" showbutton="false" increment ="0" />
                </div>
                <div field="mFPrice" name="mFPrice" width="70" numberFormat="#0.00" headerAlign="center" align="right">成本单价
                    <!--<input property="editor" class="mini-spinner" maxValue="99999999" style="width:100%;"changeOnMousewheel ="false" showbutton="false" increment ="0" />-->
                </div>
                <div field="mFAmount" name="mFAmount" numberFormat="#0.00" width="90" headerAlign="center" align="right" summaryType="sum">成本金额
                    <!--<input property="editor" class="mini-spinner" maxValue="99999999" style="width:100%;"changeOnMousewheel ="false" showbutton="false" increment ="0" />-->
                </div>
                <div field="mFPurPrice" name="mFPurPrice" width="70" numberFormat="#0.00" headerAlign="center" align="right">采购单价</div>
                <div field="mFPurAmount" name="mFPurAmount" numberFormat="#0.00" width="80" headerAlign="center" align="right" summaryType="sum">采购金额</div>
                <div field="mFPosPrice" name="mFPosPrice" width="70" numberFormat="#0.00" headerAlign="center" align="right">零售单价</div>
                <div field="mFPosAmount" name="mFPosAmount" numberFormat="#0.00" width="80" headerAlign="center" align="right" summaryType="sum">零售金额</div>
                <div field="mFCode" name="mFCode" width="120" headerAlign="center">商品条码</div>                
                <div field="mFStockQty" name="mFStockQty" width="70" headerAlign="center" align="right">结存数量</div>
                <div field="mFRemark" name="mFRemark" headerCls="CellLast" width="150" headerAlign="center" >备注
                    <input property="editor" class="mini-textbox" style="width:100%;"/>
                </div>
            </div>
        </div>  
    </div>

     @Html.Partial("~/Views/Modular/Bill/FooterEx.cshtml")
       
    </form>
    @Html.Partial("~/Views/Modular/Bill/ScanWinRmo.cshtml")
    <input id="type" name="type" value="@ViewBag.type" type="hidden"/>
    <input id="billid" name="type" value="@ViewBag.billid" type="hidden"/>

    <!--menu-->
    <ul id="popupMenu" class="mini-menu" style="display:none;">      
        <li id ="import" name="import" iconCls="icon-redo" onclick="ExcelImport">从Excel文件导入</li>        
	    <li id ="ScanAdd" name="ScanAdd" iconCls="icon-find" onclick="ScanAdd" visible="@ViewBag.save">扫描录入</li>        
    </ul>

    <script type="text/javascript">
        mini.parse();
        var form = new mini.Form("form1");
        var grid = mini.get("datagrid1");
        var uID = parent.window.getSystemAppID();
        var uCode = parent.window.getSystemAppCode();
        var uName = parent.window.getSystemAppName();

        $(function () {
            var oBox = document.getElementById("scan");
            var oBar = document.getElementById("title");
            if (id == 0)
                BillState(0);
            InitScan();
            startDrag(oBar, oBox);
            InitGrid("DeliveryRmo");
        });

        var id = getQueryString("billid");
        if (id != null) {
            mini.getbyName("KInterID").setValue(id);
        }        
        var datatype = getQueryString("datatype");      
        $(function () {
            LoadData();
        });

        function FormShown() {
        }

        function onButtonEdit(e) {
            ShowGoods("");
        }

        function onValueChanged(e) {
            ShowGoods(e.value);
        }

        function onCellBeginEdit(e) {
            var row = e.record;

            if (typeof (row.mFQty) == "undefined") {
                if (e.field == "mFQty") {
                    e.value = 0;//防止minValue出现在输入框内
                }
            }
        }

        function onCellCommitEdit(e) {
            var row = e.record;
            var total = 0;
            var alltotal = 0; //合计金额,总计           
            if (typeof (row.mFNumber) == "undefined") {
                return;
            }

            mini.get("save").setEnabled(true);//编辑后保存按钮可用

            if (e.field == "mFQty") {
                total = row.mFPrice * e.value;
                total = total.toFixed(2);
                alltotal = alltotal.toFixed(2);

                var mPurAmount = row.mFPurPrice * e.value;
                mPurAmount = mPurAmount.toFixed(2);

                var mPosAmount = row.mFPosPrice * e.value;
                mPosAmount = mPosAmount.toFixed(2);

                grid.updateRow(row, { mFAmount: total, mFPurAmount: mPurAmount, mFPosAmount: mPosAmount });
            }

            if (e.field == "mFPrice") {
                total = row.mFQty * e.value;
                total = total.toFixed(2);
                alltotal = alltotal.toFixed(2);
                grid.updateRow(row, { mFAmount: total });
            }
            if (e.field == "mFAmount") {
                total = e.value / row.mFQty;
                total = total.toFixed(2);
                alltotal = alltotal.toFixed(2);
                if (total != "NaN") {
                    grid.updateRow(row, { mFPrice: total });
                }
            }
        }

        function onCelleditenter(e) {
            var field = e.column.headerCls;
            var row = grid.getSelected();
            var mRowNo = grid.indexOf(row) + 1;
            var mRowCount = grid.getData().length;
            if ((field == "CellLast") && (mRowNo == mRowCount)) {
                addRow();//自动添加行
                return;
            }
        }

        function onDrawCell(e) {
            var record = e.record;
        }

        function onDrawSummaryCell(e) {
            var result = e.result;
            var grid = e.sender;
            var rows = e.data;

            if (e.field == "mFAmount") {
                var totalMoney = 0;
                for (var i = 0, l = rows.length; i < l; i++) {
                    var row = rows[i];
                    var t = row.mFAmount;
                    if (isNaN(t)) continue;
                    totalMoney += parseFloat(t);
                }
                totalMoney = totalMoney.toFixed(2);
                e.cellStyle = "text-align:right";
                e.cellHtml = totalMoney;
            }

            if (e.field == "mFQty") {
                var totalQty = 0;
                for (var i = 0, l = rows.length; i < l; i++) {
                    var row = rows[i];
                    var t = row.mFQty;
                    if (isNaN(t)) continue;
                    totalQty += parseFloat(t);
                }
                totalQty = totalQty.toFixed(2);
                e.cellStyle = "text-align:right";
                e.cellHtml = totalQty;
            }

            if (e.field == "mFPurAmount") {
                var totalMoney = 0;
                for (var i = 0, l = rows.length; i < l; i++) {
                    var row = rows[i];
                    var t = row.mFPurAmount;
                    if (isNaN(t)) continue;
                    totalMoney += parseFloat(t);
                }
                totalMoney = totalMoney.toFixed(2);
                e.cellStyle = "text-align:right";
                e.cellHtml = totalMoney;
            }

            if (e.field == "mFPosAmount") {
                var totalMoney = 0;
                for (var i = 0, l = rows.length; i < l; i++) {
                    var row = rows[i];
                    var t = row.mFPosAmount;
                    if (isNaN(t)) continue;
                    totalMoney += parseFloat(t);
                }
                totalMoney = totalMoney.toFixed(2);
                e.cellStyle = "text-align:right";
                e.cellHtml = totalMoney;
            }
        }

        function NewBill() {
            var nowDate = new Date();
            mini.getbyName("FDate").setValue(nowDate);
            mini.getbyName("KInterID").setValue("0");
            mini.getbyName("FBillNo").setValue("");
            mini.getbyName("FRemark").setValue("");
            mini.getbyName("FChecker").setValue("");
            mini.getbyName("FCheckDate").setValue("");
            mini.getbyName("FApprover").setValue("");
            mini.getbyName("FApproveDate").setValue("");
            grid.setData(null);
            addRow();
            BillState(0);
        }

        function addRow() {
            var newRow = { mFDataType: 1 };
            grid.addRow(newRow, grid.getData().length);
        }

        function addRows(rowCount) {
            for (var i = 0; i < rowCount; i++) {
                addRow();
            }
        }

        function removeRow() {
            var rows = grid.getSelecteds();
            if (rows.length > 0) {
                grid.removeRows(rows, true);
                mini.get("save").setEnabled(true);
                mini.get("check").setEnabled(false);
            }
        }

        function ShowGoods(txtValue) {
            mini.get("save").setEnabled(true);
            var json = "[{";
            json = json + "'FClassID':" + "'0',";
            json = json + "'FStockID':" + "'" + mini.getbyName("FStockID").getValue() + "',";
            json = json + "'FBillType':" + "'" + datatype + "',";
            json = json + "'FSupplierID':" + "'-1',";
            json = json + "'FNumber':'" + txtValue + "',";
            json = json + "'FName':'" + "" + "',";
            json = json + "'FSystemAppID':'" + uID + "'}]";
            if ((txtValue != null) && (txtValue != "")) {
                $.post("../Bill/GetBillGoodss", { datajson: json }, function (data) {
                    var ret = mini.decode(data);
                    if (ret.data.length == 1) {
                        var row = grid.getSelected();
                        var action = ret.data[0];
                        var newaction = Extra({
                            mFItemID: action.FItemID, mFNumber: action.FNumber, mFName: action.FName, mFModel: action.FSpec,
                            mFUnitName: action.FUnitName, mFQty: 0, mFPrice: action.FPrice, mFPurPrice: action.FPurPrice,
                            mFPosPrice: action.FPosPrice, mFCode: action.FCode, mFStockQty: action.FStockQty
                        });
                        grid.updateRow(row, newaction);
                        if ((row.mFQty != "NaN") && (row.mFQty != 0)) {
                            grid.updateRow(row, {
                                mFAmount: row.mFQty * action.FPrice,
                                mFPurAmount: row.mFQty * action.FPurPrice,
                                mFPosAmount: row.mFQty * action.FPosPrice
                            });
                        }
                    }
                    else {
                        ShowGoodsWin(txtValue);
                    }
                });
            }
            else {
                ShowGoodsWin(txtValue);
            }
        }

        //选择商品表
        function ShowGoodsWin(txtValue) {
            var sStockID = mini.getbyName("FStockID").getValue();
            mini.open({
                url: "../Bill/GetBillGoods",
                title: "选择商品", width: 900, height: 500,
                onload: function () {
                    var iframe = this.getIFrameEl();
                    var data = { key: txtValue, mBillType: datatype, mStockID: sStockID, FObjectID: 0 };
                    iframe.contentWindow.SetData(data);
                },
                ondestroy: function (action) {
                    if (action) {
                        var row = grid.getSelected();
                        for (var i = 0, l = action.length; i < l; i++) {
                            var rw = action[i];
                            if (typeof (row.mFItemID) != "undefined") {
                                var ix = grid.indexOf(row);
                                ix++;
                                if (ix >= grid.getData().length) {
                                    var newRow = {
                                        mFItemID: rw.FItemID, mFNumber: rw.FNumber, mFName: rw.FName, mFModel: rw.FSpec,
                                        mFUnitName: rw.FUnitName, mFQty: 0, mFPrice: rw.FPrice, mFPurPrice: rw.FPurPrice,
                                        mFPosPrice: rw.FPosPrice, mFCode: rw.FCode, mFStockQty: rw.FStockQty
                                    };
                                    grid.addRow(Extra(newRow), grid.getData().length);
                                    row = grid.getRow(ix);
                                }
                                else {
                                    row = grid.getRow(ix);
                                    grid.cancelEdit();
                                    grid.updateRow(row, Extra({
                                        mFItemID: rw.FItemID, mFNumber: rw.FNumber, mFName: rw.FName, mFModel: rw.FSpec,
                                        mFUnitName: rw.FUnitName, mFQty: 0, mFPrice: rw.FPrice, mFPurPrice: rw.FPurPrice,
                                        mFPosPrice: rw.FPosPrice, mFCode: rw.FCode, mFStockQty: rw.FStockQty
                                    }));
                                }
                            }
                            else {
                                grid.cancelEdit();
                                var arow = {
                                    mFItemID: rw.FItemID, mFNumber: rw.FNumber, mFName: rw.FName, mFModel: rw.FSpec,
                                    mFUnitName: rw.FUnitName, mFQty: 0, mFPrice: rw.FPrice, mFPurPrice: rw.FPurPrice,
                                    mFPosPrice: rw.FPosPrice, mFCode: rw.FCode, mFStockQty: rw.FStockQty
                                };
                                var newRow = Extra(arow);
                                grid.updateRow(row, newRow);
                            }
                        }
                    }
                }
            });
        }

        function checkBill() {
            mini.confirm("确定要审核该单据吗？", "提示",
                function (action) {
                    if (action == "ok") {
                        setcheckBill();
                    }
                }
           );
        }

        function setcheckBill() {
            BillState(2);
            var kid = mini.getbyName("KInterID").value;
            var json = "[{";
            json = json + "'KInterID':'" + kid + "',";
            json = json + "'FDataType':'" + datatype + "',";
            json = json + "'FSystemAppID':'" + uID + "'}]";
            BillState(5);
            $.ajax({
                url: '../Bill/CheckBillData',
                data: { mdatajson: json },
                type: "post",
                cache: false,
                success: function (txt) {
                    var ret = mini.decode(txt);
                    mini.showMessageBox({
                        showModal: false, width: 250, title: "提示", iconCls: "mini-messagebox-info",
                        message: ret.Status, timeout: 3000, x: "right", y: "bottom"
                    });

                    if (ret.id != -1) {
                        mini.getbyName("KInterID").setValue(ret.id);
                        BillState(2);
                        var nowDate = new Date();
                        mini.getbyName("FChecker").setValue(uName);
                        mini.getbyName("FCheckDate").setValue(nowDate);
                    }
                    else {
                        mini.alert("异常:" + ret.Status);
                        BillState(1);
                    }
                },
                error: function (xhr) {
                    mini.alert("异常:" + xhr.responseText);
                    BillState(1);
                }
            });
        }

        function ApproveBill() {
            mini.confirm("确定要确认收货吗？", "提示",
                function (action) {
                    if (action == "ok") {
                        setApproveBill();
                    }
                }
           );
        }

        function setApproveBill() {
            var kid = mini.getbyName("KInterID").value;
            var json = "[{";
            json = json + "'KInterID':'" + kid + "',";
            json = json + "'FDataType':'" + datatype + "',";
            json = json + "'FSystemAppID':'" + uID + "'}]";
            BillState(0);
            $.ajax({
                url: '../Bill/ApproveBillData',
                data: { mdatajson: json },
                type: "post",
                cache: false,
                success: function (txt) {
                    var ret = mini.decode(txt);
                    mini.showMessageBox({
                        showModal: false, width: 250, title: "提示", iconCls: "mini-messagebox-info",
                        message: ret.Status, timeout: 3000, x: "right", y: "bottom"
                    });

                    if (ret.id != -1) {
                        mini.getbyName("KInterID").setValue(ret.id);
                        BillState(5);
                    }
                    else {
                        mini.alert("异常:" + ret.Status);
                        BillState(2);
                    }
                },
                error: function (xhr) {
                    mini.alert("异常:" + xhr.responseText);
                    BillState(2);
                }
            });
        }


        function modify() {
            BillState(4);
            SetItemdisable(true);
            try {
                mini.get("ScanAdd").setEnabled(true);
            } catch (e) {
            }

        }

        function SetItemdisable(state) {
            var form = new mini.Form("DivHeader")
            var controls = form.getFields();
            for (var i = 0; i < controls.length; i++) {
                if (controls[i] != undefined) {
                    if (state == false) {
                        controls[i].disable();
                    }
                    else {
                        controls[i].enable();
                    }
                }
            }
        }

        function getBillData() {
            mini.open({
                url: "../Bill/FindBill",
                title: "查看单据", width: 900, height: 530,
                onload: function () {
                    var iframe = this.getIFrameEl();
                    var data = { BillKind: datatype };
                    iframe.contentWindow.SetData(data);
                },
                ondestroy: function (action) {
                    if (action) {
                        if ((action.KInterID == null) || (action.KInterID == "undefined")) return;
                        mini.getbyName("KInterID").setValue(action.KInterID);
                        LoadData();
                    }
                }
            });
        }

        function BillState(flag) {
            switch (flag) {
                case 0:   //新增
                    try {
                        mini.get("addrow").setEnabled(true);
                        mini.get("delrow").setEnabled(true);

                    } catch (e) { }
                    mini.get("check").setEnabled(false);
                    mini.get("save").setEnabled(false);
                    mini.get("modify").setEnabled(false);
                    mini.get("Approve").setEnabled(false);
                    mini.get("ScanAdd").setEnabled(true);
                    SetItemdisable(true);
                    grid.setAllowCellEdit(true);
                    mini.getbyName("txtCheckFlag").setValue("未审核");
                    break;
                case 1:   //保存
                    try {
                        mini.get("addrow").setEnabled(false);
                        mini.get("delrow").setEnabled(false);
                    } catch (e) { }
                    mini.get("check").setEnabled(true);
                    mini.get("save").setEnabled(false);
                    mini.get("modify").setEnabled(true);
                    mini.get("Approve").setEnabled(false);
                    mini.get("ScanAdd").setEnabled(false);
                    SetItemdisable(false);
                    grid.setAllowCellEdit(false);
                    mini.getbyName("txtCheckFlag").setValue("未审核");
                    break;
                case 2:   //审核
                    try {
                        mini.get("addrow").setEnabled(false);
                        mini.get("delrow").setEnabled(false);
                    } catch (e) { }
                    mini.get("check").setEnabled(false);
                    mini.get("save").setEnabled(false);
                    mini.get("modify").setEnabled(false);
                    mini.get("Approve").setEnabled(true);
                    mini.get("ScanAdd").setEnabled(false);
                    SetItemdisable(false);
                    grid.setAllowCellEdit(false);
                    mini.getbyName("txtCheckFlag").setValue("已审核");
                    break;
                case 3:   //关帐
                case 5:   //审批
                    try {
                        mini.get("addrow").setEnabled(false);
                        mini.get("delrow").setEnabled(false);
                    } catch (e) { }
                    mini.get("check").setEnabled(false);
                    mini.get("save").setEnabled(false);
                    mini.get("modify").setEnabled(false);
                    mini.get("Approve").setEnabled(false);
                    mini.get("ScanAdd").setEnabled(false);
                    SetItemdisable(false);
                    grid.setAllowCellEdit(false);
                    mini.getbyName("txtCheckFlag").setValue("已关帐");
                    if (flag == 5) mini.getbyName("txtCheckFlag").setValue("已审批");
                    break;
                case 4:   //修改后
                    try {
                        mini.get("addrow").setEnabled(true);
                        mini.get("delrow").setEnabled(true);
                    } catch (e) { }
                    mini.get("check").setEnabled(false);
                    mini.get("save").setEnabled(true);
                    mini.get("modify").setEnabled(false);
                    mini.get("Approve").setEnabled(false);
                    mini.get("ScanAdd").setEnabled(true);
                    SetItemdisable(true);
                    grid.setAllowCellEdit(true);
                    mini.getbyName("txtCheckFlag").setValue("未审核");
                    break;
            }
        }

        function dateToStr(datetime, htype) {
            if (datetime == null) datetime = new Date();
            var year = datetime.getFullYear();
            var month = datetime.getMonth() + 1; //js从0开始取 
            var date = datetime.getDate();
            if (month < 10) {
                month = "0" + month;
            }
            if (date < 10) {
                date = "0" + date;
            }
            if (htype == 1) {
                var time = year + "-" + month + "-" + date + " 00:00:00";
            }
            else {
                var time = year + "-" + month + "-" + date + " 23:59:59";
            }
            return time;
        }

        var dateformat = function (time, format) {
            var t = new Date(time);
            var tf = function (i) {
                return (i < 10 ? '0' : '') + i
            };
            return format.replace(/yyyy|MM|dd|HH|mm|ss/g,
            function (a) {
                switch (a) {
                    case 'yyyy':
                        return tf(t.getFullYear());
                        break;
                    case 'MM':
                        return tf(t.getMonth() + 1);
                        break;
                    case 'mm':
                        return tf(t.getMinutes());
                        break;
                    case 'dd':
                        return tf(t.getDate());
                        break;
                    case 'HH':
                        return tf(t.getHours());
                        break;
                    case 'ss':
                        return tf(t.getSeconds());
                        break;
                }
            });
        }

        function LoadData() {
            var minterid = mini.getbyName("KInterID").value;
            $.ajax({
                url: '../Bill/GetBillData',
                data: { mSystemAppID: uID, mBillID: minterid, mDataType: datatype },
                dataType: 'text',
                async: false,
                success: function (text) {
                    var dataR = mini.decode(text);
                    grid.setData(dataR.datadetail);
                    if (dataR.datamaster.length > 0) {
                        var mdata = dataR.datamaster[0];
                        form.setData(mdata);
                        mini.getbyName("FRStockID").setValue(mdata.FGetStockID);
                        mini.getbyName("FRStockID").setText(mdata.FGetStNumber);
                        mini.getbyName("FRStockName").setValue(mdata.FGetStName);
                        mini.getbyName("FStockID").setValue(mdata.FSetStockID);
                        mini.getbyName("FStockID").setText(mdata.FSetStNumber);
                        mini.getbyName("FStockName").setValue(mdata.FSetStName);                        
                        if (mdata.FApproveFlag == 1) {
                            BillState(5);
                        } if (mdata.FCheckFlag == 1) {
                            BillState(2);
                            mini.getbyName("ScanAdd").setEnabled(false);
                        }
                        else {
                            BillState(1);
                            mini.getbyName("ScanAdd").setEnabled(false);
                        }
                        if ((mdata.KInterID == "0") || (mdata.KInterID == null)) {
                            newBills();
                        }
                    }
                    else {
                        newBills();
                    }
                }
            });
        }

        function newBills() {
            NewBill();
            var date = new Date();
            mini.getbyName("FBillDate").setValue(date);
        }

        function checkValid() {
            if ((mini.getbyName("FBillerID").getValue() == "") || (mini.getbyName("FBillerID").getValue() == "0")) {
                var newbillerid = parent.window.getSystemAppID();
                mini.getbyName("FBillerID").setValue(newbillerid);
            }

            var MainData = form.getData();
            if (MainData.FRStockID.toString() == "") {
                mini.alert("设置错误:收货门店不能为空!");
                return false;
            }
            if (MainData.FStockID.toString() == "") {
                mini.alert("设置错误:配送门店不能为空!");
                return false;
            }
            if (mini.getbyName("FStockID").getValue() == mini.getbyName("FRStockID").getValue()) {
                mini.alert("设置错误:收货门店和配送门店不能相同!");
                return false;
            }
            return true;
        }

        function saveBill() {
            BillState(1);//先锁定
            if (checkValid() == false) {
                BillState(4);//先锁定
                return;
            }
            var MainData = form.getData();
            var cDate = mini.getbyName("FDate").getFormValue();
            var rCnt = grid.getData().length;
            var sBillNo = MainData.FBillNo;

            var mjson = "[{'KInterID':'" + MainData.KInterID + "',";
            mjson = mjson + "'FBillNo':'" + MainData.FBillNo + "',";
            mjson = mjson + "'FSystemAppID':'" + uID + "',";
            mjson = mjson + "'FGetStockID':'" + MainData.FRStockID + "',";
            mjson = mjson + "'FSetStockID':'" + MainData.FStockID + "',";
            mjson = mjson + "'FDate':'" + cDate + "',";
            mjson = mjson + "'FDataType':'" + datatype + "',";
            mjson = mjson + "'FRemark':'" + MainData.FRemark + "',";
            var json = "'goods_list':[";
            for (var i = 0; i < rCnt; i++) {
                var rs = grid.getRow(i);
                if (typeof (rs.mFNumber) == "undefined") continue;
                js = "{"              
                js = js + '"mFItemID":' + rs.mFItemID + ",";
                var qty = typeof (rs.mFQty) == "undefined" ? 0 : rs.mFQty;
                js = js + '"mFQty":' + qty + ",";
                var price = typeof (rs.mFPrice) == "undefined" ? 0 : rs.mFPrice;
                js = js + '"mFPrice":' + price + ",";
                var money = typeof (rs.mFAmount) == "undefined" ? 0 : rs.mFAmount;
                js = js + '"mFAmount":' + money + ",";
                var remark = typeof (rs.mFRemark) == "undefined" ? "" : rs.mFRemark;
                js = js + '"mFRemark":"' + remark + '"';
                js = js + "}"
                json = json + js + ","

            }
            json = json.substring(0, json.length - 1);
            json = json + "]";
            if (json.length < 8) {
                mini.alert("没有要保存的数据！");
                return;
            }
            mjson = mjson + json + "}]";
            $.ajax({
                url: '../Bill/SaveBillData_Rmo',
                data: { mdatajson: mjson },
                type: "post",
                cache: false,
                success: function (txt) {
                    var ret = mini.decode(txt);
                    if (ret.id != -1) {
                        mini.showTips({ content: '保存成功', state: "success", x: "center", y: "top", timeout: 3000 });
                        mini.getbyName("KInterID").setValue(ret.id);
                        mini.getbyName("FBillNo").setValue(ret.FBillNo);
                        BillState(1);
                    }
                    else {
                        mini.alert("异常:" + ret.Status);
                        BillState(1);
                    }
                },
                error: function (xhr) {
                    mini.alert("异常:" + xhr.responseText);
                    BillState(1);
                }
            });
        }

        function Extra(obj) {
            try {
                if (typeof (ExtraFunc) == "function") {
                    return ExtraFunc(obj);
                }
                else {
                    return obj;
                }
            } catch (e) {
                return obj;
            }
        }
        function ExcelImport() {
            var FSystemAppID = parent.window.getSystemAppID();
            mini.open({
                url: "../Bill/ImportData?mDataType=20&mSystemAppID=" + FSystemAppID + "&FStockID=" + mini.getbyName("FStockID").getValue(),
                title: "Excel导入", width: 450, height: 200,
                ondestroy: function (action) {
                    if (action == "close")
                        return;
                    if (action) {
                        if (action.length > 0) {
                            if (grid.getData().length > 0) {
                                if (grid.getData()[grid.getData().length - 1].mFNumber == undefined) {
                                    var row = grid.getRow(grid.getData().length - 1);
                                    grid.removeRow(row, false);
                                }
                            }
                            for (var i = 0, l = action.length; i < l; i++) {
                                var rw = action[i];
                                var newRow = {
                                    mFItemID: rw.mFItemID, mFNumber: rw.mFNumber, mFName: rw.mFName, mFModel: rw.mFModel,
                                    mFUnitName: rw.mFUnitName, mFQty: rw.mFQty, mFPrice: rw.mFPrice, mFCode: rw.mFCode,
                                    mFStockQty: rw.FStockQty, mFPosPrice: rw.mFPosPrice, mFPurPrice: rw.mFPurPrice, mFQty_Pra: 0,
                                    mFQty_DawOut: 0, mFEntryID_DawOut: 0, mFInterID_Pra: 0, mFEntryID_Pra: 0,
                                    mFInterID_DawOut: 0, mFBillNO_Pra: '', mFBillNO_DawOut: '', mFAmount: rw.mFAmount,
                                    mFPurAmount: rw.mFPurPrice * rw.mFQty, mFPosAmount: rw.mFPosPrice * rw.mFQty
                                };
                                grid.addRow(newRow, grid.getData().length);
                            }
                            BillState(4);
                            mini.get("ScanAdd").setEnabled(true);
                        }
                    }
                }
            });
        }
    </script>
</body>
